// 页面加载时获取数据
window.onload = function () {
    fetchMoney();
    fetchAvailableCharacters();
};

// 获取可购买的角色
function fetchAvailableCharacters() {
    fetch('/api/shop/available-characters')
        .then(response => response.json())
        .then(data => {
            const grid = document.getElementById('characterGrid');
            grid.innerHTML = '';

            data.forEach(character => {
                const canBuy = character.price <= parseInt(document.getElementById('currentMoney').textContent);
                const card = createShopCharacterCard(character, canBuy);
                grid.appendChild(card);
            });
        })
        .catch(error => console.error('获取角色列表失败:', error));
}

// 创建角色卡片
function createShopCharacterCard(character, canBuy) {
    const card = document.createElement('div');
    card.className = `character-card ${canBuy ? '' : 'disabled'}`;

    card.innerHTML = `
    <img class="character-image" src="${character.imageUrl || 'https://via.placeholder.com/280x200?text=角色立绘'}" alt="${character.name}">
    <div class="character-info">
        <div class="character-name">${character.name}</div>
        <div class="character-description">${character.introduction}</div>
        <div class="price-container">
            <span class="price ${canBuy ? '' : 'insufficient'}">${character.price} 金币</span>
        </div>
        <button class="buy-button"
                onclick="purchaseCharacter(${character.id})"
                ${canBuy ? '' : 'disabled'}>
            购买
        </button>
    </div>
`;

    return card;
}

// 购买角色
function purchaseCharacter(characterId) {
    if (confirm('确定要购买这个角色吗？')) {
        fetch('/api/shop/purchase-character', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ characterId: characterId })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 刷新金钱和角色列表
                fetchMoney();
                fetchAvailableCharacters();
            } else {
                alert('购买失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('购买失败:', error);
            alert('购买失败，请稍后重试');
        });
    }
}